import React, { useState, useEffect } from "react";
import { Form, Input, Cascader, Button, Toast, Switch } from "antd-mobile";
import "./index.css";
import addressApi from '@/api/iap/address';
import { useNavigate, useSearchParams } from "react-router-dom";

/**
 * 地址新增/编辑组件
 * 支持地址三级选择、表单校验、默认地址设置、编辑回显
 */
export default () => {
  const [form] = Form.useForm();
  const [visible, setVisible] = useState(false);
  const [addressCodes, setAddressCodes] = useState([]);
  const [btnLoading, setBtnLoading] = useState(false);
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const [addressTree, setAddressTree] = useState([]);

  // 初始化：加载地址树 + 编辑时回显地址详情
  useEffect(() => {
    const initAddressData = async () => {
      try {
        // 1. 加载地址树并获取返回的实际数据（不依赖state）
        const treeData = await getAddressTree();

        // 2. 若存在编辑ID，使用返回的treeData直接进行处理
        const editId = searchParams.get('id');
        if (editId) {
          // 直接传递treeData给getAddressInfo，确保数据可用
          await getAddressInfo(editId, treeData);
        }
      } catch (error) {
        console.error('地址数据初始化失败:', error);
        Toast.show({ content: '数据加载失败', type: 'fail' });
      }
    };

    initAddressData();
  }, [searchParams]);

  /**
   * 加载地址树并转换为Cascader所需格式
   * @returns {Array} 格式化后的地址树数据（确保同步获取）
   */
  const getAddressTree = async () => {
    const formatTree = (items) => {
      if (!Array.isArray(items)) return [];
      return items.map(item => ({
        label: item.name,
        value: item.id,
        children: item.children.length > 0 ? formatTree(item.children) : null
      }));
    };

    const res = await addressApi.address_tree();
    const formattedTree = formatTree(res.data);
    // 同时更新state和返回数据
    setAddressTree(formattedTree);
    return formattedTree; // 关键：返回实际数据
  };

  /**
   * 根据地址ID获取详情并填充表单
   * @param {string} id - 地址ID
   * @param {Array} treeData - 地址树数据（从getAddressTree直接传递，确保可用）
   */
  const getAddressInfo = async (id, treeData) => {
    try {
      const res = await addressApi.address_get({ id });
      const addressData = res.data;

      // 使用传递的treeData而非state中的addressTree
      const codes = getCodePath(addressData.areaId, treeData);
      setAddressCodes(codes);

      // 拼接地址名称
      const addressName = codes.map(code => getAddressName(code, treeData)).filter(Boolean).join(' ');

      // 填充表单
      form.setFieldsValue({
        name: addressData.name,
        mobile: addressData.mobile,
        address: addressName,
        detailAddress: addressData.detailAddress,
        defaultStatus: Boolean(addressData.defaultStatus)
      });
    } catch (error) {
      console.error('地址详情加载失败:', error);
      Toast.show({ content: '地址详情加载失败', type: 'fail' });
    }
  };

  /**
   * 递归查找地址编码的完整路径
   * @param {string|number} targetCode - 目标子级编码
   * @param {Array} tree - 地址树数据（优先使用参数传递的最新数据）
   * @returns {Array} 完整编码路径
   */
  const getCodePath = (targetCode, tree = addressTree) => {
    if (!Array.isArray(tree) || tree.length === 0) return [];

    const target = String(targetCode);
    for (const node of tree) {
      if (String(node.value) === target) {
        return [node.value];
      }

      if (Array.isArray(node.children) && node.children.length > 0) {
        const childPath = getCodePath(targetCode, node.children);
        if (childPath.length > 0) {
          return [node.value, ...childPath];
        }
      }
    }

    return [];
  };

  /**
   * 根据编码查找对应的地址名称
   * @param {string|number} code - 地址编码
   * @param {Array} tree - 地址树数据
   * @returns {string} 地址名称
   */
  const getAddressName = (code, tree = addressTree) => {
    if (!Array.isArray(tree) || tree.length === 0) return '';

    const targetCode = String(code);
    for (const node of tree) {
      if (String(node.value) === targetCode) {
        return node.label;
      }

      if (Array.isArray(node.children) && node.children.length > 0) {
        const childName = getAddressName(code, node.children);
        if (childName) return childName;
      }
    }

    return '';
  };

  const handleAddressConfirm = (selectedCodes) => {
    setAddressCodes(selectedCodes);
    const addressName = selectedCodes.map(code => getAddressName(code)).filter(Boolean).join(' ');
    form.setFieldsValue({ address: addressName });
    setVisible(false);
  };

  const handleSubmit = async () => {
    try {
      const formValues = await form.validateFields();
      const editId = searchParams.get('id');
      const returnUrl = searchParams.get('returnUrl') || '/address';

      const submitData = {
        name: formValues.name,
        mobile: formValues.mobile,
        areaId: addressCodes.at(-1) || null,
        detailAddress: formValues.detailAddress,
        defaultStatus: Boolean(formValues.defaultStatus)
      };
      if (editId) submitData.id = editId;

      setBtnLoading(true);
      if (editId) {
        await addressApi.address_update(submitData);
      } else {
        await addressApi.address_create(submitData);
      }

      Toast.show({
        content: `地址${editId ? '编辑' : '添加'}成功`,
        duration: 1500,
        type: 'success'
      });
      navigate(returnUrl);
    } catch (error) {
      if (error.errorFields) {
        Toast.show({ content: '请完善信息并确保格式正确', duration: 1500, type: 'fail' });
      } else {
        console.error('地址提交失败:', error);
        Toast.show({ content: '地址提交失败，请重试', duration: 1500, type: 'fail' });
      }
    } finally {
      setBtnLoading(false);
    }
  };

  const mobileReg = /^1[3-9]\d{9}$/;

  return (
    <div className="editAddress">
      <div className="order-header">{searchParams.get('id') ? '编辑' : '新增'}地址</div>

      <Form form={form} requiredMarkStyle="asterisk">
        <Form.Item
          name="name"
          label="姓名"
          rules={[
            { required: true, message: '请输入姓名' },
            { min: 2, message: '姓名至少2个字符' }
          ]}
        >
          <Input placeholder="请输入姓名" />
        </Form.Item>

        <Form.Item
          name="mobile"
          label="手机号"
          rules={[
            { required: true, message: '请输入手机号' },
            { pattern: mobileReg, message: '请输入正确的手机号格式' }
          ]}
        >
          <Input placeholder="请输入手机号" type="tel" />
        </Form.Item>

        <Form.Item
          name="address"
          label="地址"
          rules={[{ required: true, message: '请选择地址' }]}
        >
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {form.getFieldValue('address') || '未选择地址'}
            </div>
            <Button size="mini" color="success" style={{ marginLeft: '10px' }} onClick={() => setVisible(true)}>
              选择地址
            </Button>
          </div>
        </Form.Item>

        <Form.Item
          name="detailAddress"
          label="详细地址"
          rules={[
            { required: true, message: '请输入详细地址' },
            { min: 5, message: '详细地址至少5个字符' }
          ]}
        >
          <Input placeholder="请输入门牌号等详细信息" />
        </Form.Item>

        <Form.Item name="defaultStatus" label="默认地址">
          <Switch
            checked={form.getFieldValue('defaultStatus') || false}
            onChange={(checked) => form.setFieldsValue({ defaultStatus: checked })}
          />
        </Form.Item>

        <div style={{ marginTop: 20, padding: '0 16px' }}>
          <Button
            color="primary"
            loading={btnLoading}
            block
            onClick={handleSubmit}
            style={{ height: 48 }}
          >
            确定
          </Button>
        </div>
      </Form>

      <Cascader
        options={addressTree}
        placeholder="请选择地址"
        visible={visible}
        onConfirm={handleAddressConfirm}
        onClose={() => setVisible(false)}
        value={addressCodes}
        level={3}
      />
    </div>
  );
};
